/*
 * redmicro all Copyright (c) 
 * Created by seeker910 on 2015/6/30.
 * 外键字段输入
 */
Rsd.define('Rsd.form.TextFK', {
    extend: 'Rsd.form.Text',
    requires:[],
    xtype: 'text-fk',
    border:false, 
    /**
     * 提供给 外部操作按钮的 配置信息
     */
    selector:{},
    
    /** 
    * 
    */
    constructor: function TextFK (config) {
     
        this.apply(config||{}); 
    },
    /**
     * 
     */
    onAfterInit:function onAfterInit()
    {
        this.callParent();
        this.ctrl.element.setAttribute('readonly',true);
        var _fk_modelType  = Rsd.template(this.selector.modelType,{});
         
        if(!Rsd.isEmpty(_fk_modelType))
        {
            //提前请求
            Rsd.app.getSchema(_fk_modelType,function(schema){}); 
        } 
    },
     /**
      * 
      * @param {*} value 该控件值
      * @param {*} data FormModel控制的整个Model对象记录
      * @returns 
      */
    setValue:function setValue(value,data) {

        var me =this;
        me.__value = value ;
        //console.log('text-fk set value',me.selector,value);

        if(me.ctrl.element)
        { 
             if(!me.selector.textMember)
             {
                console.error('The text-fk control selector config must contains [textMember] field.',me);
                return;
             }
            //console.log('this is text-fk control', me,data);

            //方案1:StructToken

            
            //方案2:使用formatString 代替键值显示（关联视图对象扩展字段或冗余存储字段）
            if(me.formatString)
            { 
                var _txt = Rsd.template(me.formatString, data);
                 me.ctrl.element.value = _txt || '';
                return;
            }

            //方案3:启动本地缓存，且该类数据缓存在本地，优先从本地缓存获取
            if (value && Rsd.app.indexedDb) {
                console.log('从indexedDb中 查询数据' + me.selector.modelType);
                //从本地浏览器缓存获取
                Rsd.app.indexedDb.getObjectByKey(me.selector.modelType, value, function (obj) {

                    if (obj) {
                        var _txt = Rsd.template(me.selector.textMember, obj);
                        me.ctrl.element.value = _txt || '';
                    }
                    else {
                        me.ctrl.element.value = value;
                    } 
                }); 

                return;
            }
 
            //方案4:API查询(仅外键是string key时有效)，通过API查询获取外键对象信息，一般后端接口会缓存请求数据 
            if(value && Rsd.isString(value))
            { 
                var _data = data || {};
                //selector.modelType 当modelType是动态指定时，它是一个字符串模板
                var _fk_modelType = Rsd.template(this.selector.modelType, _data);

                Rsd.app.getSchema(_fk_modelType, function(schema){
                     if(schema)
                     {
                        schema.findObject(value , function (resp) {

                                if (resp.success && resp.data) {
                                    //console.log(me.selector.textMember, resp);
                                    var _txt = Rsd.template(me.selector.textMember, resp.data||{});
                                    me.ctrl.element.value = _txt || '';
                                }
                                else {
                                    me.ctrl.element.value = value;
                                }
                            });
                     }
                });

                return ;
            }   
            
            me.ctrl.element.value = value;
        } 
    },

     /**
     *
     * */
    getValue:function getValue() {

        return this.__value;
    },
    /**
     * 
     */
    btn_show_selector:function btn_show_selector(sender,evt)
    { 
        if(this.readonly)
        {
            return;
        }
        if(Rsd.isEmpty(this.selector.modelType))
        {
            console.error("控件Rsd.form.TextFK属性selector.modelType为空。");
        }
       
        var cols = this.selector.gridColumns||[];
         
        var me = this;
        if(Rsd.isEmpty(this.selector.viewerType))
        {
            Rsd.showMessage('该控件selector属性未找到viewerType的值。');
            return;
        }
        // 
        //console.log(_where.value,me.parent.parent.getRecord()); 
        var _data = me.parent.parent.data || {};
        if (me.parent.parent.getData) {
            _data = me.parent.parent.getData();
        } 

        var _fk_modelType = Rsd.template(this.selector.modelType,_data);
        if(Rsd.isEmpty(_fk_modelType))
        {
            Rsd.showMessage('请先设置关联字段');
            return;
        }
        var _key_member = Rsd.template(this.selector.keyMember,_data); 
        var _where = this.selector.filter||[];  
        if(!Rsd.isEmpty(_where) && Rsd.isObject(_where))
        { 
            //格式化value
            _where = [{
                name:_where.name,
                op:_where.op,
                value: Rsd.template(_where.value,_data)
            }];
        }

        //console.log(this.selector.modelType,_fk_modelType,_key_member,_data,cols);
        Rsd.create(this.selector.viewerType||'Rsd.zen.dialog.ChooseDialog',{
            readonly:true,
            autoLoad:true,
            title:this.selector.title || ('请选择-'+me.label.content),  
            modelType:_fk_modelType, 
            chooseColumn:{
                xtype:'checkbox',
                text:Rsd.lang('form.text.selector.chooseColumnText'),
                width:60,
                fixed:true,
                multiple:this.selector.multiple,
                align:'center',
                keyMember:_key_member,
                dataIndex:'_sel_' + _key_member,
                editable:true, 
            },
            where:_where,
            sort:this.selector.sort,
            gridColumns:cols,
            width:this.selector.width||800,
            height:this.selector.height||600,
            newButtons:this.selector.newButtons,
            buttons: [
                {
                    text:Rsd.lang('form.text.selector.okText'),
                    width:120,
                    handler:function(rows,btn){
                        //全部数据，非选择数据
                        //console.log(rows);
                        if (me.selector.multiple) {
                            //暂未实现多选
                            console.error('暂未实现多选');
                        }

                        var row = null;
                        for (var i = 0; i < rows.length; i++) {
                            row = rows[i];
                            if (row['_sel_' + _key_member]) {
                                break;
                            }
                            row = null;
                        }

                        if (row) {
                            //设置 修改的值 
                            me.__value = row[_key_member];//console.log(me.__value,row);
                            var _text = Rsd.template(me.selector.textMember, row);
                            me.ctrl.element.value = _text || row[_key_member] || '-';

                            //处理联动字段 ，联动字段可以有多个
                            if (me.linkages && me.linkages.length > 0) {
                                for (var i in me.linkages) {
                                    var linkage = me.linkages[i];
                                    var linkage_value = row[linkage.valueMemberName];
                                    var linkage_field = me.parent.getItemByName(linkage.targetField);
                                    //console.log(linkage,row,linkage_field,linkage_value);
                                    linkage_field.setValue(linkage_value);

                                }
                            }
                            btn.parent.close();
                            return;
                        }
                        //console.log(me.getValue());
                        Rsd.popup('请选择一条数据');
                        return;
                    }
                }
            ],
            parent:this,
            footBar:this.selector.footBar||{xtype:'container',height:40,width:'100%',border:true},
            showItem:function(){}

        }).showDialog();

    },
    /*
     * 返回 对象或数组
     * */
    makeControl:function makeControl(config,row)
    {
        if(Rsd.isEmpty(row))
        {
            return[];
        }
    
        var _config = config ||{};
        var _editable = _config.editable;
        var _dataIndex = _config.dataIndex|| _config.dataindex || _config.name;
        var _value = row[_dataIndex];
        if(_value==undefined)
        {
            //字段不存在
            return document.createTextNode(_config.emptyText ||'-');
        }
        
        var _isStructToken = false;
        
        if(_value != null && Rsd.isString(_value) && _value != '')
        {
            var _key = "";
            var _desc = "";
            var _index_key = _value.indexOf(':');
            var _index_desc = _value.indexOf('|');
            if(_index_key > 0 && _index_desc > 0)
            {
                _isStructToken = true;
                _key = _value.substring(_index_key,_index_desc-1);
                _desc = _value.substring(_index_desc + 1);
            }
            else
            {
                _key = _value;
            }

            if(Rsd.app.indexedDb)
            { 
                //浏览器缓存获取
                Rsd.app.indexedDb.getObjectByKey(_config.selector.modelType,_key,function(obj){
                    if(obj)
                    {
                        _txt = obj[config.selector.textMember]; 
                    }
                    else
                    {
                        _txt = _desc||_value; 
                    }    
                });  
            }
            else
            {
                 _txt = _desc||_value;
               
                console.error("启动时 Rsd.app.indexedDb 未初始化");
            }    
        }
        else
        {
            _txt = _value||_config.emptyText ||'';
        }

        var _ctrl_fk = document.createElement('a');
        _ctrl_fk.innerHTML= "&nbsp;"+_txt+"&nbsp;";
        _ctrl_fk.title = "查看关联对象";
        //_ctrl_fk.style.float = 'right';
        _ctrl_fk.href = "javascript:void(0)";
        _ctrl_fk.onclick = function()
        {
            alert("Error:Rsd.form.TextFK 列查看关联对象未实现");
        };


        //debugger; 
        if(_editable)
        {
             var _ctrl_edit = document.createElement('a');
             _ctrl_edit.innerHTML= "&nbsp;✏️&nbsp;"
             _ctrl_edit.title = "修改[" + (_config.text||"") + "]数据";
             //_ctrl_edit.style.float = 'right';
             _ctrl_edit.href = "javascript:void(0)";
             _ctrl_edit.onclick = function()
             {
                 alert("Error:Rsd.form.TextFK列编辑模式未实现");
             }  

            
             return [_ctrl_fk,Rsd.blankspace(2,{}),_ctrl_edit];
        }
          
        return [_ctrl_fk];
    }
  
},function(type){

    
    var _selectorGetter = function () {

        return this.___selector;
    };

    var _selectorSetter = function (value) {
        
        if(Rsd.isEmpty(value))
        {
            this.___selector = null;
            return;
        }
        this.___selector = Rsd.apply({
            //className 如： 'Rsd.zen.dialog.ChooseDialog'
            viewerType:'Rsd.zen.dialog.ChooseDialog',
            //外键对象类型
            modelType:null,
            where:null,
            sort:null, 
            style:null,
            text:Rsd.lang('form.text.selector.chooseButtonText'),
            /**
             * 选择器窗体标题
             */
            title:'',
            keyMember:'Id',
            textMember:'',
            multiple:false,
            handler:'btn_show_selector'

        },value); 
    }

    this.defineProperty(type,"selector", _selectorGetter, _selectorSetter,false);
});
